import speech_recognition as sr
from moviepy.editor import *

import wave
import matplotlib.pyplot as plt
import numpy as np
import pyaudio

def speech(file):
    '''
    语音文件翻译
    '''
    r = sr.Recognizer()  # 调用识别器
    test = sr.AudioFile(file)  # 导入语音文件
    with test as source:
        audio = r.record(source)
    type(audio)
    c = r.recognize_sphinx(audio, language='zh-cn')  # 识别输出
    print(c)


def mp4_to_wav():
    '''
    mp4提取音频
    '''
    video = VideoFileClip('test.mp4')
    audio = video.audio
    audio.write_audiofile('test.wav')


def plt_voice():
    '''
    绘制声音波形图像
    '''
    import numpy as np
    import wave
    import matplotlib.pyplot as plt
    wlen = 512
    inc = 128
    f = wave.open(r"./TEST-py/test.wav", "rb")
    params = f.getparams()
    nchannels, sampwidth, framerate, nframes = params[:4]
    str_data = f.readframes(nframes)
    # print(str_data[:10])
    wave_data = np.fromstring(str_data, dtype=np.short)
    # print(wave_data[:10])
    wave_data = wave_data * 1.0 / (max(abs(wave_data)))
    # print(wave_data[:10])
    time = np.arange(0, wlen) * (1.0 / framerate)
    signal_length = len(wave_data)  # 信号总长度
    if signal_length <= wlen:  # 若信号长度小于一个帧的长度，则帧数定义为1
        nf = 1
    else:  # 否则，计算帧的总长度
        nf = int(np.ceil((1.0 * signal_length - wlen + inc) / inc))
    pad_length = int((nf - 1) * inc + wlen)  # 所有帧加起来总的铺平后的长度
    zeros = np.zeros((pad_length - signal_length,))  # 不够的长度使用0填补，类似于FFT中的扩充数组操作
    pad_signal = np.concatenate((wave_data, zeros))  # 填补后的信号记为pad_signal
    indices = np.tile(np.arange(0, wlen), (nf, 1)) + np.tile(np.arange(0, nf * inc, inc),
                                                             (wlen, 1)).T  # 相当于对所有帧的时间点进行抽取，得到nf*nw长度的矩阵
    # print(indices[:2])
    indices = np.array(indices, dtype=np.int32)  # 将indices转化为矩阵
    frames = pad_signal[indices]  # 得到帧信号
    a = frames[30:31]
    # print(a[0])
    windown = np.hanning(512)
    b = a[0] * windown
    c = np.square(b)
    plt.figure(figsize=(10, 4))
    plt.plot(time, c, c="g")
    plt.grid()
    plt.show()

def start_audio(time=3, save_file="test_get.wav"):
    '''
    系统录音保存为文件
    '''
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 16000
    RECORD_SECONDS = time  # 需要录制的时间
    WAVE_OUTPUT_FILENAME = save_file  # 保存的文件名

    p = pyaudio.PyAudio()  # 初始化
    print("录音ON")

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)  # 创建录音文件
    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)  # 开始录音

    print("录音OFF")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')  # 保存
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

def delete_voice(file_path):
    '''
    删除文件
    '''
    os.remove(file_path)

speech("D:\项目集\python项目\智能小车\PaddleSpeech-develop\Test_zjy\myPython\Transfor\您好，欢迎使用智能小车.wav")
